import { Pattern } from "./EmbroideryPattern";
import { pecColors, Color } from "./EmbroideryColor";

export const pecReadStitches = (file, pattern) => {
    let val1,
        val2,
        jump,
        trim,
        byteCount = file.byteLength;
    while (file.tell() < byteCount) {
        val1 = file.getUint8();
        val2 = file.getUint8();

        if (val1 === 0xff && val2 === 0x00) {
            pattern.end();
            break;
        }
        if (val1 === 0xfe && val2 === 0xb0) {
            file.getInt8();
            pattern.colorChange(0, 0);
        } else {
            jump = false;
            trim = false;

            if (val1 & 0x80) {
                if (val1 & 0x20) {
                    trim = true;
                }
                if (val1 & 0x10) {
                    jump = true;
                }
                val1 = ((val1 & 0x0f) << 8) + val2;
                if (val1 & 0x800) {
                    val1 -= 0x1000;
                }
                val2 = file.getUint8();
            } else if (val1 >= 0x40) {
                val1 -= 0x80;
            }

            if (val2 & 0x80) {
                if (val2 & 0x20) {
                    trim = true;
                }
                if (val2 & 0x10) {
                    jump = true;
                }
                val2 = ((val2 & 0x0f) << 8) + file.getUint8();
                if (val2 & 0x800) {
                    val2 -= 0x1000;
                }
            } else if (val2 > 0x3f) {
                val2 -= 0x80;
            }

            if (jump) {
                pattern.move(val1, val2);
            } else if (trim) {
                pattern.trim(0, 0);
                pattern.move(val1, val2);
            } else {
                pattern.stitch(val1, val2);
            }
        }
    }

    pattern.end();
};

export const pesRead = (file) => {
    const pattern = new Pattern();
    let x, len, start;
    start = file.getInt32(8, true);
    file.seek(start + 48);
    len = file.getInt8() + 1;
    for (x = 0; x < len; x += 1) {
        pattern.addColor(pecColors[file.getInt8()]);
    }
    file.seek(start + 532);
    pecReadStitches(file, pattern);

    return pattern;
};
